package com.xh.bussiness.tiku.controller;

import com.xh.bussiness.permission.bean.dto.UserDataRuleBean;
import com.xh.bussiness.permission.service.IUserService;
import com.xh.bussiness.system.model.Dictionary;
import com.xh.bussiness.system.service.IDictionaryService;
import com.xh.bussiness.tiku.bean.dto.BookVersionChapterDto;
import com.xh.bussiness.tiku.model.BookChapter;
import com.xh.bussiness.tiku.service.IBookChapterService;
import com.xh.core.annotation.ExcludeLoginTokenIntercept;
import com.xh.core.util.StringUtils;
import com.xh.core.util.UserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.xh.bussiness.tiku.bean.request.BookVersionRequest;
import com.xh.bussiness.tiku.model.BookVersion;
import com.xh.bussiness.tiku.service.IBookVersionService;
import com.xh.core.bean.AjaxResult;
import com.xh.core.constant.AjaxResultConstant;
import com.xh.core.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @author jqm
 * @since 2019/9/11
 */
@Api(tags="教材接口")
@RestController
@RequestMapping("/tiku/bookVersion")
public class BookVersionController  extends BaseController {

    public static final Logger log = LoggerFactory.getLogger(BookVersionController.class);

    @Autowired
    private IBookVersionService bookVersionService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IBookChapterService chapterService;
    @Autowired
    private IDictionaryService dictionaryService;
//    /**
//     * 分页查询
//     */
//    @ApiOperation(value = "教材分页查询", notes = "教材分页查询")
//    @PostMapping("/queryPage")
//    public XhPage queryPage(XhPage page, BookChapterRequest request) {
//        return bookChapterService.queryBookChapterPage(page,request);
//    }

    /**
     * 数据查询
     * @return
     * @throws Exception 
     */
    @ApiOperation(value="查询所有教材", notes = "查询所有教材")
    @PostMapping("/queryAll")
    public AjaxResult queryAll(BookVersionRequest bean) throws Exception {

        return new AjaxResult(AjaxResultConstant.Result.SUCCESS,bookVersionService.queryBookVersion(bean));
    }

    /**
     * 数据查询
     * @param request
     * @return
     * @throws Exception 
     */
    @ApiOperation(value="查询所有教材", notes = "查询所有教材")
    @PostMapping("/queryVresion")
    public AjaxResult queryVresion(BookVersionRequest bean) throws Exception {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS,bookVersionService.queryVresion(bean));
    }

    /**
     * 查询教材课本树
     * @param
     * @return
     * @throws Exception
     */
    @ApiOperation(value="查询教材课本树", notes = "查询教材课本树")
    @PostMapping("/queryVresionBookTree")
    public AjaxResult queryVresionBookTree(HttpServletRequest request, BookVersionRequest bean) throws Exception {
        if(StringUtils.isEmpty(bean.getSubject())){
            return new AjaxResult(AjaxResultConstant.Result.ERROR,"参数错误");
        }
        bean.setUserId(request.getHeader("userId"));
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS,bookVersionService.queryVersionBookTree(bean));
    }

    /**
     * 添加教材
     * @param bookVersion
     * @return
     */
    @ExcludeLoginTokenIntercept
    @ApiOperation(value="添加教材", notes = "添加教材")
    @PostMapping("/addBookVersion")
    public AjaxResult addOrUpdateBookVersion(@RequestBody BookVersion bookVersion) {
        return new AjaxResult(bookVersionService.addOrUpdateBookVersion(bookVersion));
    }

    @PostMapping("/deleteById")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult deleteById(String id){
        bookVersionService.delete(id);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    /**
     * 节点移动
     * @param bookVersionId 章节id
     * @param moveType -1：下移；1：上移
     * @return
     */
    @RequestMapping("/moveUpOrDownBookVersion")
    @Transactional
    public AjaxResult moveUpOrDownBookVersion(String bookVersionId, Integer moveType) {
        return new AjaxResult(bookVersionService.moveUpOrDownBookVersion(bookVersionId, moveType));
    }


    /**
     * 查询学科下的教材版本以及课本
     * @param subjectCode
     * @return
     */
    @RequestMapping("/queryBookVersionBySubjectCode")
    public AjaxResult queryBookVersionBySubjectCode(String subjectCode) {
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, bookVersionService.queryBookVersionBySubject(subjectCode));
    }

    /**
     * 模糊查询查询学科下的教材版本以及课本
     * @param
     * @return
     */
    @RequestMapping("/queryLikeBookVersionBySubjectCode")
    public AjaxResult queryLikeBookVersionBySubjectCode(@RequestBody BookVersion request) {

        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, bookVersionService.queryLikeDictionaryByCourseSystem(request.getSubject(),request.getName()));
    }

    /**
     * 上移下移
     * @author 赵文博
     * @date 2021/4/14 17:19
     * @param bookVersions
     * @return com.xh.core.bean.AjaxResult
     **/
    @PostMapping("/updateSort")
    public AjaxResult updateSort(@RequestBody List<BookVersion> bookVersions){
        bookVersionService.updateSort(bookVersions);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }

    /**
     * 查询用户教材版本权限
     * @param request
     * @return
     */
    @ExcludeLoginTokenIntercept
    @RequestMapping("/queryUserBookVersion")
    public AjaxResult queryUserBookVersion(HttpServletRequest request,BookVersionRequest bookVersionRequest) {
        bookVersionRequest.setUserId(UserUtils.getCurrentUserId());
        UserDataRuleBean userDataRuleBean = userService.userDataRules(request.getHeader("userId"), bookVersionRequest.getSubject());
        if (userDataRuleBean == null || CollectionUtils.isEmpty(userDataRuleBean.getBookVersions())) {
            log.error("user data permission is null");
            return new AjaxResult(AjaxResultConstant.Result.SUCCESS, new ArrayList<>());
        }
        List<String> versionIds = userDataRuleBean.getBookVersions().stream().map(item -> item.getId()).collect(Collectors.toList());
        List<Dictionary> dictionaries = dictionaryService.queryDicByIds(versionIds);
        List<BookVersionChapterDto>  result = new ArrayList<>();
        for (Dictionary dictionary : dictionaries) {
            BookVersionChapterDto dto = new BookVersionChapterDto();
            dto.setId(dictionary.getId());
            dto.setName(dictionary.getName());
            bookVersionRequest.setVersionId(dictionary.getId());
            List<BookVersion> books = bookVersionService.queryBookVersion(bookVersionRequest);
            if(!books.isEmpty()){
                dto.setChilds(books);
            }
            result.add(dto);
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, result);
    }

    @RequestMapping("/queryUserBookVersion1")
    public AjaxResult queryUserBookVersion1(HttpServletRequest request,BookVersionRequest bookVersionRequest) {
        UserDataRuleBean userDataRuleBean = userService.userDataRules(request.getHeader("userId"), bookVersionRequest.getSubject());
        if (userDataRuleBean == null || CollectionUtils.isEmpty(userDataRuleBean.getBookVersions())) {
            log.error("user data permission is null");
            return new AjaxResult(AjaxResultConstant.Result.SUCCESS, new ArrayList<>());
        }
        List<String> versionIds = userDataRuleBean.getBookVersions().stream().map(item -> item.getId()).collect(Collectors.toList());
        bookVersionRequest.setBookVersionIds(versionIds);
        List<BookVersion> bookVersions = bookVersionService.queryBookVersion(bookVersionRequest);
        List<BookVersionChapterDto>  result = new ArrayList<>();
        for (int i = 0; i < bookVersions.size(); i++) {
            BookVersion bookVersion = bookVersions.get(i);
            BookVersionChapterDto dto = new BookVersionChapterDto();
            BeanUtils.copyProperties(bookVersion,dto);
            //查课本
            String versionId = bookVersion.getId();
            bookVersionRequest.setVersionId(versionId);

            List<BookVersion> books = bookVersionService.queryBookVersion(bookVersionRequest);
            for (BookVersion book : books){
                List<BookChapter> bookChapters = chapterService.queryBookChapterKnowledgeTree(book.getId());
                book.setChilds(bookChapters);
            }
            dto.setChilds(books);
            result.add(dto);
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, result);
    }
}
